package com.lenovo.vod.player.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Set;

import com.lenovo.vod.player.Constant;

public class M3u8Parser {

	private String mFirstLevelUrl;
	private HashMap<String, String> mDefinationUrlMap = new HashMap<String, String>();

	private String mFirstLevelIndex;

	private boolean mIsFirstLevel;

	public void setFirstLevelUrl(String urlStr)
	{
		mFirstLevelUrl = (urlStr.split("\\?"))[0];

		// cut /index.m3u8
		int pos = mFirstLevelUrl.indexOf("/index.m3u8");
		
		if (pos > 0) 
		{
			mFirstLevelUrl = mFirstLevelUrl.substring(0, pos + 1);
		}

		// the last char should be /
		char lastChar = mFirstLevelUrl.charAt(mFirstLevelUrl.length()-1);
		
		if (lastChar != '/') 
		{
			mFirstLevelUrl = mFirstLevelUrl + "/";
		}
	}

	public void getIndexFile(String urlStr)
	{
		try 
		{
			String str = "";
			mIsFirstLevel = true;

			// check httplive
			if (urlStr.startsWith("httplive"))
			{
				urlStr = "http" + urlStr.substring(8);
			}

			URL url = new URL(urlStr);
			String lineStr;
			BufferedReader bufReader;
			bufReader = new BufferedReader(new InputStreamReader(url
					.openStream()));
			
			while ((lineStr = bufReader.readLine()) != null)
			{
				if (lineStr.contains(".ts"))
				{
					mIsFirstLevel = false;
					return;// just parse first level
				}
				str += lineStr;
				str += "\n";
			}
			
			bufReader.close();

			mFirstLevelIndex = new String(str);
		} 
		catch (MalformedURLException e)
		{
			System.out.println("MalformedURLException:" + e);
		}
		catch (IOException e)
		{
			System.out.println("IOException:" + e);
		}
	}

	public void parseFirstLevelIndex() 
	{
		int bitrate;

		// get every line string
		String[] lines = mFirstLevelIndex.split("\n");

		for (String line : lines) {
			// skip # line
			if (line.charAt(0) == '#') {
				continue;
			}

			// get every para in a line
			String paras[] = line.split("&");

			for (String para : paras) 
			{
				if (para.startsWith(Constant.LABEL_BITRATE))
				{
					bitrate = Integer.parseInt(para.split("=")[1]);

					if (bitrate > Constant.BITRATE_STANDARD_LOWER_LIMIT  && 
						bitrate < Constant.BITRATE_STANDARD_HIGHER_LIMIT )
					{
						mDefinationUrlMap.put(
								Constant.PARA_DEFINITION_STANDARD,
								mFirstLevelUrl + line);
					} 
					else if(bitrate > Constant.BITRATE_HIGH_LOWER_LIMIT  && 
							bitrate < Constant.BITRATE_HIGH_HIGHER_LIMIT ) 
					{
						mDefinationUrlMap.put(Constant.PARA_DEFINITION_HIGH,
								mFirstLevelUrl + line);
					} 
					else if(bitrate > Constant.BITRATE_SUPER_LOWER_LIMIT  && 
							bitrate < Constant.BITRATE_SUPER_HIGHER_LIMIT )
					{
						mDefinationUrlMap.put(Constant.PARA_DEFINITION_SUPER,
								mFirstLevelUrl + line);
					}
				}
			}
		}
	}

	public void parse(String urlStr) 
	{
		if (urlStr.startsWith("http")) 
		{
			getIndexFile(urlStr);

			if (mIsFirstLevel) 
			{
				setFirstLevelUrl(urlStr);
				parseFirstLevelIndex();
			}
		}
	}

	public String getSecondLevelUrl(String defination) {
		return mDefinationUrlMap.get(defination);
	}

	public String[] getDefinations() 
	{
		Set<String> resultSet = mDefinationUrlMap.keySet();
		String[] result = new String[resultSet.size()];
		return resultSet.toArray(result);
	}
}